# 项目负责人管理
from BlackWidow.tools import tools
from django import forms
from django.forms.models import model_to_dict
from BlackWidow.models import Project, User, ProjectLeader, ProjectSubPlan
from django.http import JsonResponse
from BlackWidow.apis.user.manage import model_to_dict_with_url as user_model_to_dict_with_url

def model_to_dict_with_time(model):
    """
    将模型对象转换为字典，并处理时间字段
    Args:
        model: 模型对象
    Returns:
        dict: 处理后的字典数据
    """
    model_dict = model_to_dict(model)
    # 将负责人转换为字典
    model_dict['leader_user'] = user_model_to_dict_with_url(model.leader_user)
    # 将项目信息转换为字典
    model_dict['project'] = model_to_dict(model.project)
    model_dict['project']['project_leader'] = user_model_to_dict_with_url(model.project.project_leader)
    # 将子计划信息转换为字典
    model_dict['sub_plan_project'] = model_to_dict(model.sub_plan_project)
    model_dict['sub_plan_project']['sub_plan_total_leader'] = user_model_to_dict_with_url(model.sub_plan_project.sub_plan_total_leader)
    model_dict['create_time'] = model.create_time.strftime('%Y-%m-%d %H:%M:%S')
    model_dict['update_time'] = model.update_time.strftime('%Y-%m-%d %H:%M:%S')
    return model_dict


class ProjectLeaderModelForm(forms.ModelForm):
    """
    项目负责人表单类
    用于验证和处理项目负责人数据的表单
    """
    class Meta:
        model = ProjectLeader
        fields = [
            'project',
            'sub_plan_project',
            'leader_user',
            'leader_remark'
        ]

    def clean_project(self):
        """
        项目验证
        确保项目存在且用户有权限
        """
        project = self.cleaned_data.get('project')
        if not project:
            raise forms.ValidationError('项目不能为空')
        return project

    def clean_sub_plan_project(self):
        """
        子计划验证
        确保子计划存在且属于指定项目
        """
        sub_plan = self.cleaned_data.get('sub_plan_project')
        project = self.cleaned_data.get('project')
        
        if not sub_plan:
            raise forms.ValidationError('子计划不能为空')
        
        if sub_plan.project != project:
            raise forms.ValidationError('子计划不属于指定项目')
        
        return sub_plan

    def clean_leader(self):
        """
        负责人验证
        确保负责人不是项目总负责人
        """
        leader_user = self.cleaned_data.get('leader_user')
        project = self.cleaned_data.get('project')
        
        if not leader_user:
            raise forms.ValidationError('负责人不能为空')
        
        if leader_user == project.project_leader:
            raise forms.ValidationError('不能将项目总负责人设置为子计划负责人')
        
        return leader_user


def add_project_leader(request):
    """
    添加项目负责人
    处理项目负责人添加请求
    Args:
        request: HTTP请求对象
    Returns:
        JsonResponse: 包含操作结果的JSON响应
    """
    if request.method == 'POST':
        form = ProjectLeaderModelForm(request.POST)
        if form.is_valid():
            try:
                # 验证当前用户是否是项目负责人或子计划负责人
                project = form.cleaned_data['project']
                sub_plan = form.cleaned_data['sub_plan_project']
                
                if (project.project_leader.user_id != request.user.user_id and 
                    sub_plan.sub_plan_total_leader.user_id != request.user.user_id):
                    return JsonResponse(tools.ReturnData(1, '无权限添加负责人'))
                
                # 创建负责人记录
                leader = form.save()
                
                # 返回负责人信息
                leader_data = model_to_dict_with_time(leader)
                return JsonResponse(tools.ReturnData(0, '添加成功', data=leader_data))
            except Exception as e:
                return JsonResponse(tools.ReturnData(1, f'添加失败: {str(e)}'))
        else:
            return JsonResponse(tools.ReturnData(1, '添加失败', tools.get_first_error(form)))
    else:
        return JsonResponse(tools.ReturnData(1, '请求方式错误'))


def update_project_leader(request):
    """
    更新项目负责人
    处理项目负责人更新请求
    Args:
        request: HTTP请求对象
    Returns:
        JsonResponse: 包含操作结果的JSON响应
    """
    if request.method == 'POST':
        leader_id = request.POST.get('leader_id')
        if not leader_id:
            return JsonResponse(tools.ReturnData(1, '负责人ID不能为空'))

        try:
            leader = ProjectLeader.objects.get(leader_id=leader_id)
            # 验证当前用户是否是项目负责人或子计划负责人
            if (leader.project.project_leader.user_id != request.user.user_id and 
                leader.sub_plan_project.sub_plan_total_leader.user_id != request.user.user_id):
                return JsonResponse(tools.ReturnData(1, '无权限修改负责人'))
            
            form = ProjectLeaderModelForm(request.POST, instance=leader)
            if form.is_valid():
                # 更新负责人
                leader = form.save()
                
                # 返回更新后的负责人信息
                leader_data = model_to_dict_with_time(leader)
                return JsonResponse(tools.ReturnData(0, '更新成功', data=leader_data))
            else:
                return JsonResponse(tools.ReturnData(1, '更新失败', tools.get_first_error(form)))
        except ProjectLeader.DoesNotExist:
            return JsonResponse(tools.ReturnData(1, '负责人不存在'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(1, f'更新失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(1, '请求方式错误'))


def delete_project_leader(request):
    """
    删除项目负责人
    处理项目负责人删除请求
    Args:
        request: HTTP请求对象
    Returns:
        JsonResponse: 包含操作结果的JSON响应
    """
    if request.method == 'POST':
        leader_id = request.POST.get('leader_id')
        if not leader_id:
            return JsonResponse(tools.ReturnData(1, '负责人ID不能为空'))

        try:
            leader = ProjectLeader.objects.get(leader_id=leader_id)
            # 验证当前用户是否是项目负责人或子计划负责人
            if (leader.project.project_leader.user_id != request.user.user_id and 
                leader.sub_plan_project.sub_plan_total_leader.user_id != request.user.user_id):
                return JsonResponse(tools.ReturnData(1, '无权限删除负责人'))
            
            leader.delete()
            return JsonResponse(tools.ReturnData(0, '删除成功'))
        except ProjectLeader.DoesNotExist:
            return JsonResponse(tools.ReturnData(1, '负责人不存在'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(1, f'删除失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(1, '请求方式错误'))


def get_project_leader(request):
    """
    获取项目负责人信息
    处理项目负责人查询请求
    Args:
        request: HTTP请求对象
    Returns:
        JsonResponse: 包含操作结果的JSON响应
    """
    if request.method == 'GET':
        leader_id = request.GET.get('leader_id')
        project_id = request.GET.get('project_id')
        sub_plan_id = request.GET.get('sub_plan_id')
        
        try:
            if leader_id:
                # 获取单个负责人
                leader = ProjectLeader.objects.get(leader_id=leader_id)
                leader_data = model_to_dict_with_time(leader)
                return JsonResponse(tools.ReturnData(0, '获取成功', data=leader_data))
            elif project_id and sub_plan_id:
                # 获取指定项目和子计划的负责人列表
                leaders = ProjectLeader.objects.filter(project_id=project_id, sub_plan_project_id=sub_plan_id)
                leaders_data = [model_to_dict_with_time(leader) for leader in leaders]
                return JsonResponse(tools.ReturnData(0, '获取成功', data=leaders_data))
            elif project_id:
                # 获取指定项目的负责人列表
                leaders = ProjectLeader.objects.filter(project_id=project_id)
                leaders_data = [model_to_dict_with_time(leader) for leader in leaders]
                return JsonResponse(tools.ReturnData(0, '获取成功', data=leaders_data))
            else:
                return JsonResponse(tools.ReturnData(1, '负责人ID或项目和子计划ID不能为空'))
        except ProjectLeader.DoesNotExist:
            return JsonResponse(tools.ReturnData(1, '负责人不存在'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(1, f'获取失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(1, '请求方式错误'))


def get_user_leader_projects(request):
    """
    获取用户作为负责人的项目列表
    处理用户负责项目查询请求
    Args:
        request: HTTP请求对象
    Returns:
        JsonResponse: 包含操作结果的JSON响应
    """
    if request.method == 'GET':
        try:
            # 获取用户作为负责人的项目列表
            leaders = ProjectLeader.objects.filter(leader_user=request.user.user_id)
            
            # 按创建时间倒序排序
            leaders = leaders.order_by('-create_time')
            leaders_data = [model_to_dict_with_time(leader) for leader in leaders]
            return JsonResponse(tools.ReturnData(0, '获取成功', data=leaders_data))
        except Exception as e:
            return JsonResponse(tools.ReturnData(1, f'获取失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(1, '请求方式错误'))
